package cn.codexin.wechatofficial.controller;

import cn.codexin.wechatofficial.dto.WeChatXmlDTO;
import cn.codexin.wechatofficial.wechat.WeChatProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

/**
 * Created by xinGao 2020/4/22
 */
@RestController
public class WeChatController {

    @Autowired
    private WeChatProvider weChatProvider;

    @GetMapping("/wx")
    public String get(@RequestParam(name = "signature", required = false) String signature,
                      @RequestParam(name = "timestamp", required = false) String timestamp,
                      @RequestParam(name = "nonce", required = false) String nonce,
                      @RequestParam(name = "echostr", required = false) String echostr) {
        //验证请求是否来自微信服务器
        boolean isValid = weChatProvider.checkSignature(signature, timestamp, nonce);
        System.out.println(isValid);
        String msg="signature:"+signature+" timestamp:"+timestamp+" nonce:"+nonce+" echostr:"+echostr;
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("wx.txt")),"UTF-8"));
            bw.write(msg);
            bw.close();
        } catch (Exception e) {
            System.err.println("write errors :" + e);
        }
        return isValid ? echostr : msg;
    }

    //自动回复文本消息
    @PostMapping(value = "/wx", produces = MediaType.TEXT_XML_VALUE)
    public Object post(@RequestParam(name = "signature", required = false) String signature,
                       @RequestParam(name = "timestamp", required = false) String timestamp,
                       @RequestParam(name = "nonce", required = false) String nonce,
                       @RequestBody WeChatXmlDTO data) {

        //验证消息是否来自微信服务器
        boolean isValid = weChatProvider.checkSignature(signature, timestamp, nonce);
        WeChatXmlDTO res = new WeChatXmlDTO();
        if(!isValid) return res;
        System.out.println("成功接收到一条消息");
        System.out.println(data);

        res.setToUserName(data.getFromUserName());
        res.setFromUserName(data.getToUserName());
        res.setCreateTime(System.currentTimeMillis());
        res.setMsgType("text");
        res.setContent("你好");
        return res;
    }
}